# coding=utf-8
import sys
import os
from os.path import abspath, dirname
import copy

sys.path.insert(0, abspath(dirname(__file__)))
import tkinter
from tkinter import *
import Fun
import replacer

uiName = "ReplaceProjectStr"
ElementBGArray = {}
ElementBGArray_Resize = {}
ElementBGArray_IM = {}
WINDOW = Fun.GetElement(uiName, 'Form_1')


def msg(text, title='提示'):
    Fun.MessageBox(text, title, 'info', WINDOW)


def output(text):
    Fun.InsertText(uiName, 'output', tkinter.END, text + '\n', '')


class UiData:
    def __init__(self):
        self.DATA = {
            'project_dir': '',
            'old_str': '',
            'new_str': '',
            'file_name': True
        }

    def get_ui_data(self):
        for name in self.DATA:
            if isinstance(self.DATA[name], str):
                self.DATA[name] = Fun.GetText(uiName, name)
            elif isinstance(self.DATA[name], bool):
                self.DATA[name] = Fun.GetCurrentValue(uiName, name)
            else:
                raise '取值错误'
        res = self.check_ui_data()
        if res is False:
            return None
        return copy.deepcopy(self.DATA)

    def check_ui_data(self):
        path = self.DATA.get('project_dir')
        if not os.path.isdir(path):
            msg('项目目录必须是一个存在的文件夹路径')
            return False
        return True


uiData = UiData()
app = replacer.ReplaceTool()


# Form 'Form_1's Load Event :
def Form_1_onLoad(uiName, threadings=0):
    pass
# Button 'browser' 's Command Event :
def browser_onCommand(uiName, widgetName, threadings=0):
    openPath = Fun.SelectDirectory(title='打开目录查找', initDir=os.path.abspath('.'))
    Fun.SetText(uiName, 'project_dir', openPath)
# SwitchButton 'file_name's Switch Event :
def file_name_onSwitch(uiName, widgetName, value, threadings=0):
    value = Fun.GetCurrentValue(uiName, 'file_name')
    if value:
        Fun.SetText(uiName, 'echo_text', '替换文件名')
    else:
        Fun.SetText(uiName, 'echo_text', '不替换文件名')
#Button 'replace_button' 's Command Event :
def replace_button_onCommand(uiName,widgetName,threadings=0):
    data = uiData.get_ui_data()
    if not data:
        return
    files, content_change_files = app.replace(data)
    if files:
        info = '被改名的文件（旧名称）有：\n' + '\n'.join(files)
        output(info)
    if content_change_files:
        info = '被改变内容的文件（新名称）有：\n' + '\n'.join(content_change_files)
        output(info)
    if not files and not content_change_files:
        msg('没有需要替换的内容')
        return
    msg('替换已完成')
